﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FTP_progress
{

    public class dataGridView : IDisposable
    {
        private readonly string _connectionString;
        private readonly DataGridView _dataGridView;
        private readonly string _tableName;
        private readonly string _primaryKey;

        private SQLiteDataAdapter _dataAdapter;
        private SQLiteConnection _connection; // 添加类级连接对象
        private DataTable _dataTable;
        private int _currentPage = 1;
        private int _pageSize = 20;
        private int _totalRecords = 0;

        // 分页控件
        private Panel _pagingPanel;
        private Button _firstPageBtn;
        private Button _prevPageBtn;
        private Label _pageInfoLabel;
        private Button _nextPageBtn;
        private Button _lastPageBtn;
        private ComboBox _pageSizeCombo;

        private Dictionary<string, int> _columnWidths = new Dictionary<string, int>();
        public dataGridView(string dbPath, DataGridView dataGridView, string tableName, string primaryKey)
        {
            _connectionString = $"Data Source={dbPath};Version=3;";
            _dataGridView = dataGridView ?? throw new ArgumentNullException(nameof(dataGridView));
            _tableName = tableName ?? throw new ArgumentNullException(nameof(tableName));
            _primaryKey = primaryKey ?? throw new ArgumentNullException(nameof(primaryKey));

            InitializeDataGridView();
            InitializePagingControls();
        }

        private void InitializeDataGridView()
        {
            _dataGridView.AllowUserToAddRows = true;
            _dataGridView.AllowUserToDeleteRows = true;
            _dataGridView.ReadOnly = false;
            _dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            //_dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            _dataGridView.BackgroundColor = Color.White;
           // _dataGridView.DefaultCellStyle.SelectionBackColor = Color.LightBlue;
            // 样式设置
            _dataGridView.DefaultCellStyle.Font = new Font("Microsoft YaHei", 9);
            _dataGridView.ColumnHeadersDefaultCellStyle.Font = new Font("Microsoft YaHei", 9, FontStyle.Regular);
            _dataGridView.EnableHeadersVisualStyles = false;

           
            _dataGridView.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(240, 240, 240);
            _dataGridView.RowHeadersDefaultCellStyle.ForeColor = Color.DimGray;

            _dataGridView.AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue;
            _dataGridView.ColumnHeadersVisible = true;
            _dataGridView.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            _dataGridView.ColumnHeadersDefaultCellStyle.Alignment= DataGridViewContentAlignment.MiddleCenter;
        }

        // 新增方法：设置列宽
        public void SetColumnWidth(string columnName, int width)
        {
            _columnWidths[columnName] = width;
        }

   
        private void ApplyColumnWidths()
        {
            if (_dataGridView.Columns.Count == 0 || _columnWidths.Count == 0)
                return;

            foreach (var kvp in _columnWidths)
            {
                if (_dataGridView.Columns.Contains(kvp.Key))
                {
                    _dataGridView.Columns[kvp.Key].Width = kvp.Value;
                }
            }
        }


        private void InitializePagingControls()
        {
            _pagingPanel = new Panel
            {
                Dock = DockStyle.Bottom,
                Height = 40,
                BackColor = SystemColors.Control
            };

            // 首页按钮
            _firstPageBtn = new Button
            {
                Text = "首页",
                Size = new Size(60, 30),
                Location = new Point(10, 5),
                Enabled = false
            };
            _firstPageBtn.Click += (s, e) => GoToPage(1);

            // 上一页按钮
            _prevPageBtn = new Button
            {
                Text = "上一页",
                Size = new Size(60, 30),
                Location = new Point(80, 5),
                Enabled = false
            };
            _prevPageBtn.Click += (s, e) => GoToPage(_currentPage - 1);

            // 页码信息
            _pageInfoLabel = new Label
            {
                Text = "第 0 页 / 共 0 页",
                AutoSize = true,
                Location = new Point(150, 10),
                Font = new Font("Microsoft YaHei", 9, FontStyle.Bold)
            };

            // 下一页按钮
            _nextPageBtn = new Button
            {
                Text = "下一页",
                Size = new Size(60, 30),
                Location = new Point(250, 5)
            };
            _nextPageBtn.Click += (s, e) => GoToPage(_currentPage + 1);

            // 末页按钮
            _lastPageBtn = new Button
            {
                Text = "末页",
                Size = new Size(60, 30),
                Location = new Point(320, 5)
            };
            _lastPageBtn.Click += (s, e) => GoToPage(GetTotalPages());

            // 每页记录数选择
            _pageSizeCombo = new ComboBox
            {
                DropDownStyle = ComboBoxStyle.DropDownList,
                Items = { "10", "20", "50", "100" },
                SelectedIndex = 1,
                Size = new Size(60, 30),
                Location = new Point(400, 5)
            };
            _pageSizeCombo.SelectedIndexChanged += (s, e) =>
            {
                _pageSize = int.Parse(_pageSizeCombo.SelectedItem.ToString());
                _currentPage = 1;
                LoadData();
            };

            // 添加控件到面板
            _pagingPanel.Controls.AddRange(new Control[]
            {
            new Label { Text = "每页:", AutoSize = true, Location = new Point(470, 10) },
            _pageSizeCombo,
            _firstPageBtn,
            _prevPageBtn,
            _pageInfoLabel,
            _nextPageBtn,
            _lastPageBtn
            });

            // 将分页面板添加到DataGridView的父容器
            if (_dataGridView.Parent != null)
            {
                _dataGridView.Parent.Controls.Add(_pagingPanel);
            }
        }

        public void LoadData()
        {
            try
            {
                // 如果连接已存在，先关闭并释放
                if (_connection != null)
                {
                    _connection.Close();
                    _connection.Dispose();
                }

                // 创建新连接
                _connection = new SQLiteConnection(_connectionString);
                _connection.Open();

                

                    // 获取总记录数
                    using (var countCommand = new SQLiteCommand($"SELECT COUNT(*) FROM {_tableName}", _connection))
                    {
                        _totalRecords = Convert.ToInt32(countCommand.ExecuteScalar());
                    }

                    // SQLite分页查询 (使用LIMIT和OFFSET)
                    int offset = (_currentPage - 1) * _pageSize;
                    string query = $"SELECT * FROM {_tableName} ORDER BY {_primaryKey} LIMIT @PageSize OFFSET @Offset";

                    _dataAdapter = new SQLiteDataAdapter(query, _connection);
                    _dataAdapter.SelectCommand.Parameters.AddWithValue("@PageSize", _pageSize);
                    _dataAdapter.SelectCommand.Parameters.AddWithValue("@Offset", offset);

                    // 自动生成更新命令
                    var commandBuilder = new SQLiteCommandBuilder(_dataAdapter);
                    _dataAdapter.InsertCommand = commandBuilder.GetInsertCommand();
                    _dataAdapter.UpdateCommand = commandBuilder.GetUpdateCommand();
                    _dataAdapter.DeleteCommand = commandBuilder.GetDeleteCommand();

                    _dataTable = new DataTable();
                    _dataAdapter.Fill(_dataTable);

                    // 绑定到DataGridView
                    _dataGridView.DataSource = _dataTable;

                // 应用列宽设置
                ApplyColumnWidths();

                // 更新分页信息
                UpdatePagingInfo();
                
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void SaveChanges()
        {
            try
            {
                if (_dataAdapter == null || _dataTable == null)
                {
                    MessageBox.Show("没有可保存的数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 结束当前编辑
                _dataGridView.EndEdit();

                // 更新数据库
                int affectedRows = _dataAdapter.Update(_dataTable);

                MessageBox.Show($"成功保存 {affectedRows} 条记录!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                // 重新加载当前页数据
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存数据时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void GoToPage(int pageNumber)
        {
            int totalPages = GetTotalPages();

            if (pageNumber < 1)
                pageNumber = 1;
            else if (pageNumber > totalPages)
                pageNumber = totalPages;

            _currentPage = pageNumber;
            LoadData();
        }

        private int GetTotalPages()
        {
            return (int)Math.Ceiling((double)_totalRecords / _pageSize);
        }

        private void UpdatePagingInfo()
        {
            int totalPages = GetTotalPages();

            _pageInfoLabel.Text = $"第 {_currentPage} 页 / 共 {totalPages} 页";
            _firstPageBtn.Enabled = _currentPage > 1;
            _prevPageBtn.Enabled = _currentPage > 1;
            _nextPageBtn.Enabled = _currentPage < totalPages;
            _lastPageBtn.Enabled = _currentPage < totalPages;
        }

        public int PageSize
        {
            get => _pageSize;
            set
            {
                if (value > 0 && value != _pageSize)
                {
                    _pageSize = value;
                    _pageSizeCombo.SelectedItem = value.ToString();
                    _currentPage = 1;
                    LoadData();
                }
            }
        }

        public void Dispose()
        {
            if (_pagingPanel != null && _pagingPanel.Parent != null)
            {
                _pagingPanel.Parent.Controls.Remove(_pagingPanel);
            }
            _pagingPanel?.Dispose();
            _dataAdapter?.Dispose();
            _dataTable?.Dispose();
        }
    }

}

